<?php
	/* 
	Immanuel192 write this action on 8/12/2009 

	Change log
	Sep 12, 2011- trungdt - Add aggregate
	Remove Ajax support: we dont need
	Rewrite this action to support new style, aggregate
	*/
	global $db;
	// Used later, for recalculation and other things.
	if (!defined("SYS_SORTING")) require_once(BASE."subsystems/sorting.php");

	$config = $db->selectObject('articlemodule_config',"location_data='".serialize($loc)."'");
	if ($config == null) {
		$config->enable_categories = 0;
		$config->recalc = 0; // No need to recalculate, no categories
		$config->item_per_page = 10;
		$config->aggregate = array();
		$config->seo_name = $loc->src;
	} else  if ($config->recalc == 1) {
			// We need to recaculate the rankings.
			if ($config->enable_categories == 1) {
				// Recalc, keeping in mind the category structure.
				$cats = $db->selectObjects("category","location_data='".serialize($loc)."'");
				$c = null;
				$c->id = 0;
				$cats[] = $c;
				foreach ($cats as $c) {
					// Loop over each category.
					$rank = 0;
					foreach ($db->selectObjects("article","location_data='".serialize($loc)."' AND category_id=".$c->id) as $article) {
						$article->rank = $rank;
						$db->updateObject($article,"article");
						$rank++;
					}
				}
			} else {
				// Recaculate blindly, ignoring categories.
				$articles = $db->selectObjects("article","location_data='".serialize($loc)."'");
				usort($articles, "exponent_sorting_byRankAscending");
				$rank = 0;
				foreach ($articles as $article) {
					$article->rank = $rank;
					$article->category_id = 0;
					$db->updateObject($article,"article");
					$rank++;
				}
			}
			$config->recalc = 0;
			$db->updateObject($config,'articlemodule_config',"location_data='".serialize($loc)."'");
		}

		// get module title
		// because if the client switch page, so, that is the action and exponent does not transfer $title and $views
		$temp=$db->selectObject("container","internal = '" . serialize($loc) . "'");
	if ($temp)
	{
		$title=$temp->title;
		$view=$temp->view;
	}
	else
	{
		$title="";
		if (!isset($view))
			$view="Default";
	}

	// Create the template
	$template = new template("articlemodule",$view,$loc);
	$template->assign("config",$config);

	// 8/14/2009: Immanuel192 remove this code to get article module work with page split
	// Get all of the categories for this Article module:
	/*$cats = array();
	$cats = $db->selectObjectsIndexedArray('category', "location_data='".serialize($loc)."'");
	if ($config->enable_categories) {
	if (count($cats) != 0) {
	$template->assign('hasCategories', 1);				
	} else {
	$template->assign('hasCategories', 0);
	}
	} else {
	$template->assign('hasCategories', 0);
	}

	$c->name = '';
	$c->id = 0;
	uasort($cats, "exponent_sorting_byRankAscending");
	$cats[0] = $c;
	$template->assign('categories', $cats);

	$data = array();
	if ($config->enable_categories == true) {
	foreach ($cats as $id=>$c) {
	//Get all the questions & answers for this article module. ($qnas stands for "Questions 'n Answers")
	$tmp = $db->selectObjects("article","location_data='".serialize($loc)."' AND category_id=".$id);
	$catids = array_keys($cats); // for in_array check only
	for ($i = 0; $i < count($tmp); $i++) {
	if (!in_array($tmp[$i]->category_id,$catids)) {
	//	echo 'Setting cat id to 0<br />';
	$tmp[$i]->category_id = 0;
	}
	}
	usort($tmp, "exponent_sorting_byRankAscending");
	$data[$id] = $tmp;
	}
	} else {
	$tmp = $db->selectObjects("article","location_data='".serialize($loc)."' AND category_id=0");
	usort($tmp, 'exponent_sorting_byRankAscending');
	$data[0] = $tmp;
	}
	*/

	// build sql location WHERE condition
	$locsql = "({$db->prefix}article.location_data='".serialize($loc)."'";
	$locations=array();
	if (!empty($config->aggregate)) {
		$locations = unserialize($config->aggregate);
		foreach ($locations as $source) {
			$tmploc = null;
			$tmploc->mod = $loc->mod;
			$tmploc->src = $source;
			$tmploc->int = '';
			$locsql .= " OR {$db->prefix}article.location_data='".serialize($tmploc)."'";
		}
	}
	$locsql .= ')';

	// condition for select category
	$article_select_mod='';
	$article_select_cat='';
	if (isset($_GET['mod_select']))
	{
		$article_select_mod = $_GET['mod_select'];
	}
	if (isset($_GET['cat_select']))
	{
		$article_select_cat = $_GET['cat_select'];
	}

	// add article mod select
	if ($article_select_mod!=''){
		$locsql.=" AND ({$db->prefix}articlemodule_config.seo_name == '{$article_select_mod}') ";
	}
	// select cat condition
	if ($article_select_cat != '')
	{
		$locsql.=" AND ({$db->prefix}category.seo_name == '{$article_select_cat}') ";
	}

	// build sql
	$sql=" FROM ({$db->prefix}article INNER JOIN {$db->prefix}user
	ON {$db->prefix}user.id = {$db->prefix}article.ower_id)";
	if ($config->enable_categories == 1)
	{
		$sql.=" INNER JOIN {$db->prefix}category ON ({$db->prefix}article.location_data = {$db->prefix}category.location_data) AND ({$db->prefix}article.category_id = {$db->prefix}category.id)";
	}
	$sql.=" WHERE {$locsql}";
	// calculate how many page
	$article_count = $db->selectObjectsBySql("SELECT count({$db->prefix}article.id) count_article {$sql}"); 
	$article_count=$article_count[0]->count_article;

	$page_count=$article_count / $config->item_per_page;

	if ($article_count % $config->item_per_page > 0)
		$page_count++;

	// get all article for current page
	$page=intval($_REQUEST['page']);

	if (($page<1) || ($page>$page_count))  $page=1;
	$start_pos=($page-1)*($config->item_per_page);


	$data=$db->selectObjectsBySql("SELECT {$db->prefix}article.*, {$db->prefix}user.firstname, {$db->prefix}user.lastname, {$db->prefix}user.username   {$sql} ORDER BY rank DESC, id ASC limit {$start_pos},{$config->item_per_page}");

	// build left tree of category
	array_unshift($locations,$loc->src);

	// file ID, image id, create_date, ower_id
	foreach ($data as $k=>$value){
		// for date
		$value->create_date=_ab_dateFormat($value->create_date,true);

		// for image
		//Get the image file if there is one.
		if (isset($value->image_id) && ($value->image_id > 0)) {
			$file = $db->selectObject('file', 'id='.$value->image_id);
			$value->image_path = $file->directory.'/'.$file->filename;
		}
		else
			$value->image_path="";
		
		// for article file
		// for image
		//Get the image file if there is one.
		if (isset($value->file_id) && ($value->file_id > 0)) {
			$file = $db->selectObject('file', 'id='.$value->file_id);
			//$value->file_path = BASE_URL.$file->directory.'/'.$file->filename;
			$value->file_path = $file->filename;
		}
		else
			$value->file_path="";
		
	}

	/*
	* Aug 12, 2010: immanuel192 add this code to return all category
	*/ 
	$cats=$db->selectObjects("category","location_data='".serialize($loc)."'");

	$template->assign('submissions', $db->countObjects('article_submission', "location_data='".serialize($loc)."'"));
	$template->assign('data',$data);
	$template->assign('pages',$page_count);
	$template->assign('page',$page);
	$template->assign('cats',$cats);
	$template->register_permissions(
		array('administrate','configure','manage'),
	$loc);
	$template->assign('moduletitle', $title);
	//echo "<xmp>";
	//print_r ($data);
	//echo "</xmp>";
	if (!(isset($_REQUEST['flow_has_set']) && ($_REQUEST['flow_has_set']==1)))
		exponent_flow_set(SYS_FLOW_PUBLIC,SYS_FLOW_ACTION);
	$template->output();
?>
